package org.hackystat.projectbrowser.page.settrigger;

import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.markup.html.link.Link;
import org.hackystat.ambientdevice.server.jaxb.Project;
import org.hackystat.ambientdevice.server.jaxb.Trigger;
import org.hackystat.ambientdevice.server.jaxb.TriggerActionPair;
import org.hackystat.projectbrowser.ProjectBrowserSession;

/**
 * The Link class that deals with deleting triggers.
 * 
 * @author Sonwright M. Gomez
 * @author Edward Kim
 * 
 */
public class DeleteTriggerLink extends Link {

  private List<TriggerActionPair> pairs = new ArrayList<TriggerActionPair>();
  private String triggerId;
  private String tapName;
  private Project project;

  /**
   * Constructor
   * 
   * @param id the id.
   * @param triggerId the trigger id.
   * @param projectName the project name.
   * @param tapName the triggeractionPair name.
   */
  public DeleteTriggerLink(String id, String triggerId, String projectName, String tapName) {
    super(id);
    this.triggerId = triggerId;
    this.tapName = tapName;
    this.project = ProjectBrowserSession.get().getProjectTypeXMLByNameId(projectName);
    pairs = project.getTriggerActionPairs().getTriggerActionPair();
  }

  /**
   * Supports serialization.
   */
  private static final long serialVersionUID = 1L;

  /**
   * What happens when the user clicks on the delete link.
   */
  @Override
  public void onClick() {
    // Iterate through the pairs
    for (TriggerActionPair tapTemp : pairs) {
      List<Trigger> listTriggers = new ArrayList<Trigger>();

      // If it finds a match, then it will add it to a temporary list to be deleted later
      // The temporary list is required due to ConcurrentModificationException.
      if (tapTemp.getId().equals(this.tapName) && tapTemp.getTriggers() != null) {
        for (Trigger tempTrigger : tapTemp.getTriggers().getTrigger()) {
          if (tempTrigger.getId().equals(this.triggerId)) {
            listTriggers.add(tempTrigger);
          }
        }
        tapTemp.getTriggers().getTrigger().removeAll(listTriggers);
      }
    }
  }
}
